package com.oss.robot.link;

import java.net.URL;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.oss.model.Link;
import com.oss.robot.RetrieveRobot;
import com.oss.service.LinkService;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.fetcher.FeedFetcher;
import com.sun.syndication.fetcher.impl.FeedFetcherCache;
import com.sun.syndication.fetcher.impl.HashMapFeedInfoCache;
import com.sun.syndication.fetcher.impl.HttpURLFeedFetcher;

/**
 * 直接解析提取链接，由于InfoQ的RSS需要token限制，这里使用了一个固定的RSS链接
 * 
 * @author xueqiang.mi
 * @since 2010-7-16
 */
public class InfoQRobot implements RetrieveRobot {
	static public final String URL = "http://www.infoq.com/RSS";
	static public final String SOURCE = "InfoQ.COM";
	static public final Integer TASK_NUMBER_PER_TIME = 1;

	@Autowired
	protected LinkService lnkService;

	@Override
	public void prepareTasks() {
		throw new UnsupportedOperationException(
				"InfoQRobot can't do this operation!");
	}

	@Override
	@SuppressWarnings("unchecked")
	public void retrieveData() {
		// get RSS link
		String rssLink = getRssLink();
		// do retrieve
		FeedFetcherCache feedInfoCache = HashMapFeedInfoCache.getInstance();
		FeedFetcher feedFetcher = new HttpURLFeedFetcher(feedInfoCache);
		SyndFeed feed = null;
		try {
			feed = feedFetcher.retrieveFeed(new URL(rssLink));
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<SyndEntry> entries = feed.getEntries();
		for (SyndEntry entry : entries) {
			Link lnk = new Link();
			lnk.setSource(SOURCE);
			lnk.setName(entry.getTitle());
			String desc = entry.getDescription().getValue();
			lnk.setDescription(desc);
			lnk.setUrl(entry.getLink());
			lnkService.add(lnk);
		}
	}

	private String getRssLink() {
		return "http://www.infoq.com/rss/rss.action?token=prAqt1aBUVJYBy292pEHiE71r95TOg6u";
	}
}
